package com.crape.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.crape.common.bean.LoginUser;

public class NoLoginFilter implements Filter {

	protected FilterConfig filterConfig = null;
	private String includes; // URI白名单

	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String uri = request.getRequestURI();
		if (!uri.equals("/") && includes != null && includes.contains(uri)) {
			HttpSession session = request.getSession();
			Object userObj = session.getAttribute(LoginUser.SESSION_LOGINUSER);
			if (userObj == null) {
				request.getRequestDispatcher("/noLoginError.html").forward(request, response);
				return;
			}
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.includes = filterConfig.getInitParameter("includes");
		this.filterConfig = filterConfig;
	}

}
